<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
    <title>Student Website</title>
</head>

<body>
<div class="navbar">
        <span class="title">
            <a href="/" style="text-decoration: none; color: black">Main Page</a>
            <!-- 下拉菜单开始 -->
    <details>
        <summary style="list-style: none; color: white; cursor: pointer;">Navigation</summary>
        <ul style="list-style-type: none; padding-left: 0; background-color: #1660AB;">
        <li style="color: #F9F2E0" id="chatLink">chat</li>
        </ul>
    </details>
            <!-- 下拉菜单结束 -->
        </span>
</div>

<div>
    <h1>
        HELLO!
        <span id="username">{{ username }}</span>
    </h1>
</div>

<div style="margin-left: 60px;">
    <form id="searchForm" style="display: flex; align-items: center;">
        <label for="searchType" style="margin-right: 20px;">Search Bar:</label>
        <select id="searchType" class="input" style="margin-right: 20px;width: 400px;">
            <option value="user">User</option>
            <option value="course">Course</option>
            <option value="lecture">Lecture</option>
        </select>
        <input type="text" id="searchInput" class="input" placeholder="Enter name to search"
               style="width: 400px; margin-right: 10px;">
        <button type="button" class="button" onclick="search()"
                style="padding: 8px 15px; background-color: #1660AB; color: #fff; border: none; border-radius: 5px; cursor: pointer;">
            Search
        </button>
    </form>
    <div id="searchResult" class="result"></div>
    <!-- 在你的HTML文件中加入模态对话框的HTML结构 -->
    <div id="searchModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span> <!-- 添加一个关闭按钮 -->
            <div id="searchResultModal" class="result"></div> <!-- 这里用来放置搜索结果 -->
        </div>
    </div>
</div>

<div class="card">
    <h2>
        DeadLines
    </h2>
    <form id="deadlineForm">
        <input type="text" id="ddl_info" name="ddl_info">
        <input type="text" id="overtime" name="overtime">
    </form>
    <br>
    <div id="updatedeadlinecard" style="display: none;">
        <span>Information: </span>
        <input id="update_ddl_info" type="text" class="input">
        <br>
        <br>
        <span>which coursework: </span>
        <input id="related_hw" type="text" class="input">
        <br>
        <br>
        <button class="button" onclick="UpdateDeadline()">Update DeadLine</button>
        <button class="button" onclick="searchDDLList()">Show all DeadLines</button>
    </div>
</div>

<div class="container">
    <div class="left-column">
        <div class="card">
            <h2>
                Class
            </h2>
            <div id="classlist">
                <p>
                    No more.
                </p>
            </div>
            <button class="button" style="float: right; display: none;" onclick="window.location.href = '/newclass'"
                    id="add_new_class">
                Create a new class
            </button>
        </div>
    </div>

    <div class="right-column">
        <div class="card hidden" id="registrations">
            <h2 class="title">Register</h2>
            <div class="form-group">
                <label for="new_username">Username</label>
                <input type="text" id="new_username" name="new_username" class="form-input" required>
            </div>
            <div class="form-group">
                <label for="new_password">Password</label>
                <input type="password" id="new_password" name="new_password" class="form-input" required>
                <p></p>
                <label for="new_password">Password</label>
                <input type="password" id="new_password2" name="new_password2" class="form-input" required>
            </div>
            <div>
                <label for="assign_class">Class</label>
                <br>
                <input type="class" id="assign_class" name="assign_class" class="form-input" required>
            </div>
            <br>
            <div class="form-group">
                <label for="user_type">User Type</label>
                <br>
                <select id="user_type" class="form-input">
                    <option value="0">Student</option>
                    <option value="1">Teacher</option>
                    <option value="2">Administrator</option>
                </select>
            </div>
            <br>
            <button class="button" onclick="validateAndRegister()">Register</button>
        </div>
    </div>

</div>
<a href="/api/logout" style="text-align: center; display: block; margin: 0 auto;">
    <button class="logout-button">LOG OUT</button>
</a>

<div id="ddlModal" class="modal">
    <div class="modal-content">
        <div id="ddl-list"></div>
    </div>
</div>

</body>
<script>


    fetch('/api/class')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            const classlist = document.getElementById('classlist');
            classlist.innerHTML = '';

            data.data.forEach(classInfo => {
                const classItem = document.createElement('div');
                console.log(classInfo)
                classItem.innerHTML = `
                    <div class="card1">
                        <a href="/class?classname=${classInfo[0]}" style="text-decoration: none; color: black">
                            <h3 style="color: black">${classInfo[0]}</h3>
                            <p style="line-height: 10px; color: black">Description:
                                <p style="color: black">${truncateString(classInfo[2])}</p>
                            </p>
                    <div></div>
                        </a>
                    </div>
                `;

                classlist.appendChild(classItem);
            });

            const classItem = document.createElement('div');
            classItem.style = "text-align: center;";
            classlist.appendChild(classItem);

            const add_new_class_button = document.getElementById("add_new_class");
            const registrations_card = document.getElementById("registrations");
            const updatedeadline_card = document.getElementById("updatedeadlinecard");
            let username;

            fetch('/api/get_user_name')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    username = data;
                    var link = document.getElementById("chatLink");
                    link.href = "/chat?username=" + encodeURIComponent(username);
                    link.innerHTML = "<a href='" + link.href + "' style='text-decoration: none; color: inherit; display: inline; padding: 0;'>Chat</a>";
                    fetch(`/api/users/${username}`, {
                        method: 'GET',
                    })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            } else {
                                throw new Error('Failed to get class');
                            }
                        })
                        .then(userinfo_data => {
                            if (userinfo_data.data[2] != "0") {
                                updatedeadline_card.style.display = "block";
                                if (userinfo_data.data[2] != "1") {
                                    registrations_card.style.display = "block";
                                    add_new_class_button.style.display = "block";
                                }
                            }

                            fetch('/api/get_deadline')
                                .then(response => {
                                    if (!response.ok) {
                                        throw new Error('The network response was incorrect and the DDL information could not be obtained');
                                    }
                                    return response.json();
                                })
                                .then(data => {
                                    if (data.ddl_info && data.overtime) {
                                        const overtimeDate = new Date(data.overtime);
                                        const now = new Date();
                                        const diffMs = overtimeDate - now;
                                        const diffDays = diffMs / (1000 * 60 * 60 * 24); // 一天的毫秒数
                                        {#console.log(now)#}
                                        {#console.log(overtimeDate)#}
                                        {#console.log(diffDays)#}
                                        if (diffDays <= 7 && diffDays >= 0) {
                                            document.getElementById("ddl_info").value = data.ddl_info;
                                            document.getElementById("overtime").value = data.overtime;
                                        }
                                    } else {
                                        console.log('no deadline');
                                    }
                                })
                        })
                        .catch(error => {
                            console.error('There has been a problem with your fetch operation:', error);
                        });
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });

    function searchDDLList() {
        const url = '/api/deadlineList';
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                displayDDLList(data); // 显示ddl列表
                document.getElementById('ddlModal').style.display = "block"; // 显示弹窗
            })
            .catch(error => {
                console.error('There was an error:', error);
            });
    }

    document.addEventListener('DOMContentLoaded', function () {
        // 获取模态窗口和关闭按钮
        var modal = document.getElementById("ddlModal");


        // 如果用户点击模态窗口外的地方，也关闭它（可选）
        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    });

    function displayDDLList(data) {
        var ddlListElement = document.getElementById('ddl-list');
        ddlListElement.innerHTML = '';

        if (Array.isArray(data)) {
            // Display all DDLs
            data.forEach(ddl => {
                var ddlHtml = `
                        <div>
                            <strong>ID:</strong> ${ddl.id}<br>
                            <strong>Info:</strong> ${ddl.info}<br>
                            <strong>Overtime:</strong> ${ddl.overtime}<br>
                            <strong>Homework Name:</strong> ${ddl.hwname}<br><br>
                        </div>
                    `;
                ddlListElement.innerHTML += ddlHtml;
            });
        } else {
            // Display an error message if any
            if ('error' in data) {
                ddlListElement.innerHTML = `Error: ${data.error}`;
            } else if ('message' in data) {
                ddlListElement.innerHTML = `Message: ${data.message}`;
            }
        }
    }


    // 验证函数
    function validateAndRegister() {
        var classNmae = document.getElementById("assign_class").value;
        var username = document.getElementById('new_username').value;
        var password = document.getElementById('new_password').value;
        var pwd2 = document.getElementById('new_password2').value;
        var userType = document.getElementById('user_type').value;

        // 检查是否为空
        if (!username || !password || !userType || !classNmae) {
            alert('Please fill in all fields before registering.'); // 如果有任何一项为空，则弹出警告
        } else if (pwd2 !== password){
            alert('Please enter same password!')
        } else {
            register();
        }
    }

    function register() {
        const classname = document.getElementById("assign_class").value;
        const username = document.getElementById('new_username').value;
        const password = document.getElementById('new_password').value;
        const type = document.getElementById('user_type').value;

        fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({username: username, password: password, type: type, classname: classname})
        })
            .then(response => {
                if (response.ok) {
                    alert('User Registration Successful');
                    // 注册成功后刷新页面
                    window.location.reload();
                } else {
                    alert('Username already exists');
                }
            })
            .catch(error => {
                console.error('error:', error);
            });
    }

    function truncateString(str) {
        if (str.length > 15) {
            return str.slice(0, 15) + '...';
        } else {
            return str;
        }
    }

    function search() {
        var searchType = document.getElementById("searchType").value;
        var searchInput = document.getElementById("searchInput").value;

        var url = "/api/search?type=" + searchType + "&name=" + encodeURIComponent(searchInput);
        fetch(url)
            .then(response => response.json())
            .then(data => {
                displayResults(data, searchType);
                openModal(); // 新增：打开模态框
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function openModal() {
        document.getElementById("searchModal").style.display = "block";
    }

    function displayResults(data, searchType) {
        var searchResultModal = document.getElementById("searchResultModal");
        searchResultModal.innerHTML = ""; // 清空之前的搜索结果

        if (data.data == null) {
            alert("no result!!!")
            return;
        }

        var resultHTML = "<div>";
        data.data.forEach(item => {
            console.log(searchType)
            var id = item[0]; // 假设 id 是 item 的第一个元素
            if (searchType === 'user') {
                resultHTML += `
                    <div class="card">
                        <h2>ID: ${id}</h2>
                        <a href="/user?username=${id}"
                           style="text-decoration: none; display: flex; flex-direction: column; gap: 5px; width: 100%; padding: 10px; box-sizing: border-box; font-family: Arial, sans-serif;">
                        </a>
                    </div>
                `;
            }
            if (searchType === 'course') {
                var classname = item[1];
                var teacher = item[2];
                resultHTML += `
                    <div class="card">
                        <h2>ID: ${id}</h2>
                        <a href="/class?classname=${id}"
                           style="text-decoration: none; display: flex; flex-direction: column; gap: 5px; width: 100%; padding: 10px; box-sizing: border-box; font-family: Arial, sans-serif;">
                            <p style="color: black">Class name: ${classname}</p>
                            <p style="color: black">Teacher: ${teacher}</p>
                        </a>
                    </div>
                `;
            }
            if (searchType === 'lecture') {
                var name = item[4];
                resultHTML += `
                    <div class="card">
                        <h2>ID: ${id}</h2>
                        <a href="/lecture?lecturename=${id}"
                           style="text-decoration: none; display: flex; flex-direction: column; gap: 5px; width: 100%; padding: 10px; box-sizing: border-box; font-family: Arial, sans-serif;">
                            <p>Name: ${name}</p>
                        </a>
                    </div>
                `;
            }
        });
        resultHTML += "</div>";

        searchResultModal.innerHTML = resultHTML;
    }


    // 新增函数：关闭模态框
    document.getElementById("searchModal").addEventListener("click", function (event) {
        if (event.target == document.getElementById("searchModal")) {
            closeModal();
        }
    });

    function closeModal() {
        document.getElementById("searchModal").style.display = "none";
    }

    // 为模态弹窗的关闭按钮添加事件监听器
    document.querySelector('.close').addEventListener('click', closeModal);
    // 如果需要点击模态背景也关闭弹窗，可以添加以下代码
    window.addEventListener('click', function (event) {
        if (event.target == document.getElementById("searchModal")) {
            closeModal();
        }
    });

    // 新增函数用于显示模态弹窗
    function showModal() {
        document.getElementById("searchModal").style.display = "block";
    }

    function UpdateDeadline() {
        const rela_work = document.getElementById("related_hw").value
        const ddl_info = document.getElementById("update_ddl_info").value
        // Data to send to the server
        var data = {
            ddl_info: ddl_info,
            rela_hw: rela_work
        };

        // Configuring the fetch request
        fetch('/api/updateDeadline', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
                window.location.reload();
                // Handle success response from the server
            })
            .catch(error => {
                console.error('Error:', error);
                // Handle error
            });
    }


</script>
<style>

    .container {
        display: flex;
    }

    .left-column {
        flex: 1;
        padding: 20px;
    }

    .right-column {
        flex: 1;
        padding: 20px;
    }

    .logout-button {
        margin-left: auto;
        margin-top: 10px;
        padding: 10px 20px;
        background-color: #1660AB;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }


    .logout-button:hover {
        background-color: #3498db;
    }

    h1 {
        margin-left: 20px;
        font-family: Arial, sans-serif;
        color: #333;
        text-align: center;
        font-size: 24px;
    }

    #username {
        font-weight: bold; /* 加粗用户名 */
        color: sienna; /* 蓝色，突出用户名 */
    }

    /* CSS样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 15% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

    /* 模态框基础样式 */
    .modal {
        display: none; /* 默认隐藏模态框 */
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto; /* 允许内容滚动 */
        background-color: rgba(0, 0, 0, 0.4); /* 半透明黑色背景 */
        z-index: 1; /* 确保模态框在最上层 */
    }

    /* 模态框内容区样式 */
    .modal-content {
        background-color: lightblue; /* 浅蓝色背景 */
        margin: 15% auto; /* 居中显示 */
        padding: 20px;
        border: 1px solid #888;
        width: 80%; /* 可根据需要调整宽度 */
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        -webkit-animation-name: animatetop;
        -webkit-animation-duration: 0.4s;
        animation-name: animatetop;
        animation-duration: 0.4s;
    }

    /* 关闭按钮样式 */
    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

    /* 结果区域简单样式 */
    .result {
        margin-top: 20px;
    }

    .hidden {
        display: none;
    }

    /* 替换display: none;为类样式，便于管理 */
    .right-column {
        /* 可根据需要调整右侧栏样式 */
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-input {
        width: 80%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .register-button {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 10px 18px;
        font-size: 16px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s ease;
    }

    details {
        margin-left: 10px; /* 根据需要调整数值，正值会使其右移 */
    }

    details summary {
        font-size: 0.9em; /* 或者直接指定像素值，例如 font-size: 14px; */
    }

    details ul a {
        font-size: 0.9em; /* 同上，根据需要调整 */
    }
</style>

</html>